package com.lagou.server;

import com.lagou.handler.RPCHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 服务端
 */
@Service
public class RPCServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;

    @Autowired
    RPCHandler rpcHandler;
    //@PreDestory
    @Override
    public void destroy() throws Exception {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }

    public void init(String ip, Integer port) {
         try {
             //1. 创建线程组
             bossGroup = new NioEventLoopGroup(1); //boss线程组数为1
             workGroup = new NioEventLoopGroup();
             //2. 服务启动助手
             ServerBootstrap bootstrap = new ServerBootstrap();
             //3.设置参数
             bootstrap.group(bossGroup, workGroup)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel socketChannel) throws Exception {
                             ChannelPipeline pipeline = socketChannel.pipeline();
                             // 添加编解码器
                             pipeline.addLast(new StringDecoder());
                             pipeline.addLast(new StringEncoder());
                             //添加自定义业务处理类
                             pipeline.addLast(rpcHandler);
                         }
                     });
             // 启动服务
             ChannelFuture bind = bootstrap.bind(ip,port).sync();

             System.out.println("客户端启动成功");
             // 监听服务关闭的状态
             Channel channel = bind.channel();
             channel.closeFuture().sync();
         } catch (InterruptedException e) {
             e.printStackTrace();
             if (bossGroup != null) {
                 bossGroup.shutdownGracefully();
             }
             if (workGroup != null) {
                 workGroup.shutdownGracefully();
             }
         } finally {
             if (bossGroup != null) {
                 bossGroup.shutdownGracefully();
             }
             if (workGroup != null) {
                 workGroup.shutdownGracefully();
             }
         }
     }

}


